﻿using System;
using nRoute.Components;
using nRoute.Samples.SimpleMVVM.Views;
using nRoute.ViewModels;
using nRoute.Components.Composition;
using nRoute.Samples.SimpleMVVM.Services;

namespace nRoute.Samples.SimpleMVVM.ViewModels
{
    [MapViewModel(typeof(PageA))]
    public class PageAViewModel
        : NavigationViewModelBase
    {
        private string _text;
        private string _lastSavedAt;
        private ITimeService _timeService;

        [ResolveConstructor]
        public PageAViewModel(ITimeService timeService)
        {
            _timeService = timeService;
            _lastSavedAt = "NEVER";
        }

        public string Text
        {
            get { return _text; }
            set
            {
                if (!string.Equals(_text, value, StringComparison.InvariantCulture))
                {
                    _text = value;
                    NotifyPropertyChanged(() => Text);
                }
            }
        }

        public string LastSavedAt
        {
            get { return _lastSavedAt; }
            set
            {
                if (!string.Equals(_lastSavedAt, value, StringComparison.InvariantCulture))
                {
                    _lastSavedAt = value;
                    NotifyPropertyChanged(() => LastSavedAt);
                }
            }
        }

#region Overrides

        protected override ParametersCollection OnSaveState()
        {
            return new ParametersCollection() 
            { 
                new Parameter("TEXT", this.Text),
                new Parameter("SAVEDAT", _timeService.GetCurrentDateTime().ToLongTimeString())
            }; 
        }

        protected override void OnRestoreState(ParametersCollection state)
        {
            base.OnRestoreState(state);
            if (state != null)
            {
                if (state.ContainsKey("TEXT")) this.Text = Convert.ToString(state["TEXT"]);
                if (state.ContainsKey("SAVEDAT")) this.LastSavedAt = Convert.ToString(state["SAVEDAT"]);
            }
        }

#endregion

    }
}
